
var dataArray=[];
var dataTable = null;

var nEditing = null;

$(function() {
	
	//提示信息初始设置
	toastr.options = {
			  "closeButton": true,
			  "debug": false,
			  "positionClass": "toast-top-center",
			  "onclick": null,
			  "showDuration": "1000",
			  "hideDuration": "1000",
			  "timeOut": "5000",
			  "extendedTimeOut": "1000",
			  "showEasing": "swing",
			  "hideEasing": "linear",
			  "showMethod": "fadeIn",
			  "hideMethod": "fadeOut"
			};
	
	$("#add_plan").click(function(){
		$("#plan_file").click();
	});

	//切换图片判断类型，先设置只支持doc,docx;
	$("#plan_file").change(function(){
		asyncUploadImage();
	});

	
	$('#add_plan_table a.edit').live('click', function (e) {
        e.preventDefault();

        /* Get the row as a parent of the link that was clicked on */
        var nRow = $(this).parents('tr')[0];

        if (nEditing !== null && nEditing != nRow) {
            /* Currently editing - but not this row - restore the old before continuing to edit mode */
            restoreRow(dataTable, nEditing);
            editRow(dataTable, nRow);
            nEditing = nRow;
        } else if (nEditing == nRow && this.innerHTML == "确定") {
            /* Editing this row and want to save it */
            saveRow(dataTable, nEditing);
            nEditing = null;
            // alert("Updated! Do not forget to do some ajax to sync with backend :)");
        } else {
            /* No edit in progress - let's start one */
            editRow(dataTable, nRow);
            nEditing = nRow;
        }
    });
	
	//删除行操作（未使用）
	$('#add_plan_table a.cancel').live('click', function (e) {
        e.preventDefault();
        if ($(this).attr("data-mode") == "new") {
            var nRow = $(this).parents('tr')[0];
            dataTable.fnDeleteRow(nRow);
        } else {
            restoreRow(dataTable, nEditing);
            nEditing = null;
        }
    });
	
	
	//$("#");
	
	//$("#success_view").show();
	//showDateTable();
});




//异步上传excel暂时改成同步上传
function asyncUploadImage() {
	//判断是否有选择上传文件
	var filePath = $("#plan_file").val();
	if (filePath == "") {
		toastr.error("请选择上传计划文件！");
		return;
	}
	//判断上传文件的后缀名
	var strExtension = filePath.substr(filePath.lastIndexOf('.') + 1);
	if (strExtension != 'xls' && strExtension != 'xlsx') {
		toastr.error("请选择上传正确的Excel文件,后缀为xls,xlsx");
		return;
	}
	$('#uploadForm').submit();
	/*$.ajax({
		type: "POST",
		url: "web/showExcelHandler.htm",
		data:new FormData($('#uploadForm')[0]),
		async:true,
		cache: false,
		xhr: function() {  // custom xhr
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
            }
            return myXhr;
        },
		processData: false,
		contentType: false,
		beforeSend:function(){
			$('#show_progress').show();
			console.log("上传准备中");
		},
		success: function(successData) {
			console.log("上传成功了");
			//console.log(data);
			$('#show_progress').after().html("").append(successData.message);
			if(successData.success){
				$('#show_progress').css("color","green");
				//此处展示预览excel信息
				$("#success_view").show();
				if(dataTable!=null){
					console.log("fnDestroy table");
					dataTable.fnDestroy();
				}
				showDateTable(successData);
				
			}else{
				$('#show_progress').css("color","red");
			}
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			console.log("上传失败了");
			$('#show_progress').hide().append("很抱歉，上传失败了，请稍后重试！").css("color","red");
		}
	});*/
}

//进度条展示
function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

//读取dataTable
function showDateTable(successData) {
	if (!jQuery().dataTable) {
		return;
	}
	dataTable=$('#add_plan_table').dataTable({
		"sDom" : "<'row'<'col-md-6 col-sm-12'l><'col-md-12 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", //default layout without horizontal scroll(remove this setting to enable horizontal scroll for the table)
		/*"sAjaxSource":"web/showTableDataExcelHandler.htm",
		"fnServerData": function ( sSource, aoData, fnCallback ) {
			//aoData.push({name:"rs",value:JSON.stringify(data)});
			console.log(aoData);
			$.ajax({
				"dataType":'json',
				"type": "POST",
				"url": sSource,
				"data": aoData,
				"success": fnCallback
			});
		},*/
		//'sAjaxSource':successData.aaData,
		'fnData':successData.aaData,
		//"bDeferRender":true,
		"bInfo": true,//页脚信息
		"bFilter":false,
		"bLengthChange":false,//取消显示每页条数
		"bProcessing": false,//开关，以指定当正在处理数据的时候，是否显示“正在处理”这个提示信息
		"bPaginate": false,//开关，是否显示（使用）分页器
		"bServerSide": true,//true依据后台排序
		"bStateSave": false,//状态保存，使用了翻页或者改变了每页显示数据数量，会保存在cookie中
		"bJQueryUI":false,//是否用jquery样式
		"sZeroRecords": "没有检索到数据",
		"aoColumns": [
		              { 'mDataProp':'orderDate',"bSortable": false,"sClass": "center","sTitle":"订单时间"},
		              { 'mDataProp':'goodsName',"bSortable": false,"sClass": "center","sTitle":"商品名称",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }},
		              { 'mDataProp':'goodsType',"bSortable": false,"sClass": "center","sTitle":"商品规格",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'goodsUnit',"bSortable": false ,"sClass": "center","sTitle":"商品单位",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'goodsNum',"bSortable": false ,"sClass": "center","sTitle":"商品数量",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  console.log(data);
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'planUnit',"bSortable": false,"sClass": "center","sTitle":"客户单位",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  } 
		              },
		              { 'mDataProp':'deparmentName',"bSortable": false,"sClass": "center","sTitle":"客户部门",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'contactsName',"bSortable": false,"sClass": "center","sTitle":"客户使用人",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'employeeName',"bSortable": false,"sClass": "center","sTitle":"操作人",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'bak',"bSortable": false,"sClass": "center","sTitle":"操作",
		            	  "mRender": function ( data, type, row ) {
		            		return '<span><a class="edit btn btn-xs blue" href="javascript:;)">更改</a></span>';
		            		//+'<span><a class="btn btn-xs dark" href="javascript:;">保存</a></span>';
		            		//+'<span><a class="btn btn-xs green" href="javascript:addContacts(\''+data+'\');">添加联系人</a></span>';
		            	  }
		              }
		              ],
          "aLengthMenu": [
                          [5, 10, 15, 20,50,100],
                          [5, 10, 15, 20,50,100] // change per page values here
                          ],
          "fnCreatedRow": function( nRow, aData, iDisplayIndex ) {
              $(nRow).on('click', function (){//行click击事件
              	if($(this).hasClass("active")){
              		$(this).removeClass("active");
              	}else{
              		//$('#add_plan_table tbody tr').removeClass("active");
              		var set = jQuery(this).attr("data-set");
              		$(this).toggleClass("active");
              		jQuery.uniform.update(set);
              	}
              	dataArray.push(aData);
              });   
          },
          "bRetrieve": true, 
          "iDisplayLength": 15,
          "sPaginationType": "bootstrap",
          "oLanguage": {
        	  "sProcessing": '<i class="fa fa-coffee"></i>&nbsp;正在加载中......',
        	  "sEmptyTable" : "没有查询到数据",
        	  "sLengthMenu": "每页展示    _MENU_  条 ",
        	  "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
        	  "sInfoEmpty":"当前显示0到0条，共0条记录",
        	  "oPaginate": {
        		  "sFirst": "首页",
        		  "sPrevious": "上一页 ",
        		  "sNext": "下一页",
        		  "sLast": "末页",
        	  }
          },
          "fnInitComplete": function() {
              this.fnAdjustColumnSizing(true);
           }

	});

	jQuery('#add_plan_table .group-checkable').change(function () {
		var set = jQuery(this).attr("data-set");
		var checked = jQuery(this).is(":checked");
		jQuery(set).each(function () {
			if (checked) {
				$(this).attr("checked", true);
			} else {
				$(this).attr("checked", false);
			}
			$(this).parents('tr').toggleClass("active");
		});
		jQuery.uniform.update(set);

	});

	jQuery('#add_plan_table tbody tr .checkboxes').change(function(){
		$(this).parents('tr').toggleClass("active");
	});

	/*jQuery('#add_plan_table_wrapper .dataTables_filter input').addClass("form-control input-medium"); // modify table search input
	jQuery('#add_plan_table_wrapper .dataTables_length select').addClass("form-control input-xbig"); // modify table per page dropdown
	jQuery('#add_plan_table .dataTables_length select').select2(); // initialize select2 dropdown
*/	jQuery('#add_plan_table_processing').css("text-align","center");

}

function saveRow(oTable, nRow) {
    var jqInputs = $('input', nRow);
    oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
    oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
    oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
    oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
    
    oTable.fnUpdate(jqInputs[4].value, nRow, 4, false);
    oTable.fnUpdate(jqInputs[5].value, nRow, 5, false);
    oTable.fnUpdate(jqInputs[6].value, nRow, 6, false);
    oTable.fnUpdate(jqInputs[7].value, nRow, 7, false);
    oTable.fnUpdate(jqInputs[8].value, nRow, 8, false);
    
    oTable.fnUpdate('<span><a class="edit btn btn-xs blue" href="javascript:;)">更改</a></span>', nRow, 9, false);
    //oTable.fnUpdate('<a class="delete" href="">Delete</a>', nRow, 5, false);
    //oTable.fnDraw();
}

function editRow(oTable, nRow) {
    var aData = oTable.fnGetData(nRow);
    var jqTds = $('>td', nRow);
    if(aData.orderDate==undefined||aData.orderDate==''||aData.orderDate=='NULL'||aData.orderDate=='null'){
    	jqTds[0].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.orderDate + '">';    	
    }
    
    if(aData.goodsName==undefined||aData.goodsName==''||aData.goodsName=='NULL'||aData.goodsName=='null'){
    	jqTds[1].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.goodsName + '">';
    }
    
    if(aData.goodsType==undefined||aData.goodsType==''||aData.goodsType=='NULL'||aData.goodsType=='null'){
    	jqTds[2].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[2].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.goodsType + '">';
    }
    
    if(aData.goodsUnit==undefined||aData.goodsUnit==''||aData.goodsUnit=='NULL'||aData.goodsUnit=='null'){
    	jqTds[3].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.goodsUnit + '">';
    }
    
    if(aData.goodsNum==undefined||aData.goodsNum==''||aData.goodsNum=='NULL'||aData.goodsNum=='null'){
    	jqTds[4].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[4].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.goodsNum + '">';
    }
    
    if(aData.planUnit==undefined||aData.planUnit==''||aData.planUnit=='NULL'||aData.planUnit=='null'){
    	jqTds[5].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[5].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.planUnit + '">';
    }
    
    if(aData.deparmentName==undefined||aData.deparmentName==''||aData.deparmentName=='NULL'||aData.deparmentName=='null'){
    	jqTds[6].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[6].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.deparmentName + '">';
    }
    
    if(aData.contactsName==undefined||aData.contactsName==''||aData.contactsName=='NULL'||aData.contactsName=='null'){
    	jqTds[7].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[7].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.contactsName + '">';
    }
    
    if(aData.employeeName==undefined||aData.employeeName==''||aData.employeeName=='NULL'||aData.employeeName=='null'){
    	jqTds[8].innerHTML = '<input type="text" class="form-control input-small">';
    }else{
    	jqTds[8].innerHTML = '<input type="text" class="form-control input-small" value="' + aData.employeeName + '">';
    }
    
    
    jqTds[9].innerHTML = '<span><a class="edit btn btn-xs btn-danger" href="javascript:;)">确定</a></span>';
    //jqTds[10].innerHTML = '<a class="cancel" href="">Cancel</a>';
}

function restoreRow(oTable, nRow) {
    var aData = oTable.fnGetData(nRow);
    var jqTds = $('>td', nRow);

    for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
        oTable.fnUpdate(aData[i], nRow, i, false);
    }

    oTable.fnDraw();
}
